package com.subang.function.controller;

import com.subang.common.annotation.Log;
import com.subang.common.core.controller.BaseController;
import com.subang.common.core.domain.AjaxResult;
import com.subang.common.core.page.TableDataInfo;
import com.subang.common.enums.BusinessType;
import com.subang.common.utils.poi.ExcelUtil;
import com.subang.common.utils.uuid.IdUtils;
import com.subang.function.domain.ShenlunAnswerLike;
import com.subang.function.domain.ShenlunPapers;
import com.subang.function.domain.ShenlunQuestions;
import com.subang.function.domain.ShenlunReferenceAnswers;
import com.subang.function.service.IShenlunAnswerLikeService;
import com.subang.function.service.IShenlunPapersService;
import com.subang.function.service.IShenlunQuestionsService;
import com.subang.function.service.IShenlunReferenceAnswersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 申论试卷Controller
 * 
 * @author subei
 * @date 2025-02-26
 */
@RestController
@RequestMapping("/compare/papers")
public class ShenlunPapersController extends BaseController
{
    @Autowired
    private IShenlunPapersService shenlunPapersService;

    @Autowired
    private IShenlunQuestionsService shenlunQuestionsService;

    @Autowired
    private IShenlunReferenceAnswersService shenlunReferenceAnswersService;

    @Autowired
    private IShenlunAnswerLikeService shenlunAnswerLikeService;

    /**
     * 查询申论试卷列表
     */
    /*@PreAuthorize("@ss.hasPermi('compare:papers:list')")*/
    @GetMapping("/list")
    public TableDataInfo list(ShenlunPapers shenlunPapers)
    {
        startPage();
        List<ShenlunPapers> list = shenlunPapersService.selectShenlunPapersList(shenlunPapers);
        return getDataTable(list);
    }

    /**
     * 导出申论试卷列表
     */
    @PreAuthorize("@ss.hasPermi('compare:papers:export')")
    @Log(title = "申论试卷", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ShenlunPapers shenlunPapers)
    {
        List<ShenlunPapers> list = shenlunPapersService.selectShenlunPapersList(shenlunPapers);
        ExcelUtil<ShenlunPapers> util = new ExcelUtil<ShenlunPapers>(ShenlunPapers.class);
        util.exportExcel(response, list, "申论试卷数据");
    }

    /**
     * 获取申论试卷详细信息
     */
    /*@PreAuthorize("@ss.hasPermi('compare:papers:query')")*/
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        ShenlunPapers shenlunPapers = shenlunPapersService.selectShenlunPapersById(id);

        ShenlunQuestions shenlunQuestions = new ShenlunQuestions();
        shenlunQuestions.setPaperId(id);
        
        // 获取试卷的问题列表
        List<ShenlunQuestions> questions = shenlunQuestionsService.selectShenlunQuestionsList(shenlunQuestions);

        // 将问题逐个添加到试卷中
        List<ShenlunPapers.Question> paperQuestions = new ArrayList<>();
        for (ShenlunQuestions question : questions) {
            ShenlunPapers.Question paperQuestion = new ShenlunPapers.Question();
            paperQuestion.setId(question.getId());
            paperQuestion.setDescription(question.getDescription());
            paperQuestion.setSequence(question.getSequence());
            paperQuestion.setScore(question.getScore());

            ShenlunAnswerLike shenlunAnswerLike = new ShenlunAnswerLike();
            shenlunAnswerLike.setUserId(String.valueOf(getUserId()));
            shenlunAnswerLike.setQuestionId(question.getId());
            List<ShenlunAnswerLike> list = shenlunAnswerLikeService.selectShenlunAnswerLikeList(shenlunAnswerLike);

            // 获取参考答案
            ShenlunReferenceAnswers shenlunReferenceAnswers = new ShenlunReferenceAnswers();
            shenlunReferenceAnswers.setQuestionId(question.getId());
            List<ShenlunReferenceAnswers> answers = shenlunReferenceAnswersService.selectShenlunReferenceAnswersList(shenlunReferenceAnswers);
            List<ShenlunQuestions.Answer> paperAnswers = new ArrayList<>();
            for (ShenlunReferenceAnswers answer : answers) {
                ShenlunQuestions.Answer paperAnswer = new ShenlunQuestions.Answer();
                paperAnswer.setId(answer.getId());
                paperAnswer.setContent(answer.getContent());
                paperAnswer.setAnswerType(answer.getAnswerType());
                paperAnswer.setSource(answer.getSource());
                if (!list.isEmpty() && answer.getId().equals(list.get(0).getAnswerId())) {
                    paperAnswer.setIsLiked(1L);
                } else {
                    paperAnswer.setIsLiked(0L);
                }
                paperAnswer.setLikeCount(answer.getLikeCount());
                paperAnswers.add(paperAnswer);
            }
            paperQuestion.setAnswers(paperAnswers);
            paperQuestions.add(paperQuestion);
        }
        shenlunPapers.setQuestions(paperQuestions);
        
        return success(shenlunPapers);
    }

    /**
     * 新增申论试卷
     */
    @PreAuthorize("@ss.hasPermi('compare:papers:add')")
    @Log(title = "申论试卷", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ShenlunPapers shenlunPapers)
    {
        shenlunPapers.setId(IdUtils.simpleUUID());

        // 循环新增问题和参考答案
        ShenlunQuestions shenlunQuestions = new ShenlunQuestions();
        for (ShenlunQuestions question : shenlunPapers.getQuestions()) {
            shenlunQuestions.setId(IdUtils.simpleUUID());
            shenlunQuestions.setSequence(question.getSequence());
            shenlunQuestions.setPaperId(shenlunPapers.getId());
            shenlunQuestions.setDescription(question.getDescription());
            shenlunQuestions.setScore(question.getScore());
            shenlunQuestionsService.insertShenlunQuestions(shenlunQuestions);

            ShenlunReferenceAnswers shenlunReferenceAnswers = new ShenlunReferenceAnswers();
            for (ShenlunReferenceAnswers answer : question.getAnswers()) {
                shenlunReferenceAnswers.setId(IdUtils.simpleUUID());
                shenlunReferenceAnswers.setQuestionId(shenlunQuestions.getId());
                shenlunReferenceAnswers.setContent(answer.getContent());
                shenlunReferenceAnswers.setAnswerType(answer.getAnswerType());
                shenlunReferenceAnswers.setSource(answer.getSource());
                shenlunReferenceAnswersService.insertShenlunReferenceAnswers(shenlunReferenceAnswers);
            }
        }
        return toAjax(shenlunPapersService.insertShenlunPapers(shenlunPapers));
    }

    /**
     * 修改申论试卷
     */
    @PreAuthorize("@ss.hasPermi('compare:papers:edit')")
    @Log(title = "申论试卷", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ShenlunPapers shenlunPapers)
    {
        shenlunPapersService.deleteShenlunPapersById(shenlunPapers.getId());
        shenlunQuestionsService.deleteShenlunQuestionsByPaperId(shenlunPapers.getId());
        shenlunReferenceAnswersService.deleteShenlunReferenceAnswersByPaperId(shenlunPapers.getId());
        // 循环新增问题和参考答案
        ShenlunQuestions shenlunQuestions = new ShenlunQuestions();
        for (ShenlunQuestions question : shenlunPapers.getQuestions()) {
            shenlunQuestions.setId(IdUtils.simpleUUID());
            shenlunQuestions.setSequence(question.getSequence());
            shenlunQuestions.setPaperId(shenlunPapers.getId());
            shenlunQuestions.setDescription(question.getDescription());
            shenlunQuestions.setScore(question.getScore());
            shenlunQuestionsService.insertShenlunQuestions(shenlunQuestions);

            ShenlunReferenceAnswers shenlunReferenceAnswers = new ShenlunReferenceAnswers();
            for (ShenlunReferenceAnswers answer : question.getAnswers()) {
                shenlunReferenceAnswers.setId(IdUtils.simpleUUID());
                shenlunReferenceAnswers.setQuestionId(shenlunQuestions.getId());
                shenlunReferenceAnswers.setContent(answer.getContent());
                shenlunReferenceAnswers.setAnswerType(answer.getAnswerType());
                shenlunReferenceAnswers.setSource(answer.getSource());
                shenlunReferenceAnswers.setLikeCount(answer.getLikeCount());
                shenlunReferenceAnswersService.insertShenlunReferenceAnswers(shenlunReferenceAnswers);
            }
        }
        return toAjax(shenlunPapersService.insertShenlunPapers(shenlunPapers));
    }

    /**
     * 删除申论试卷
     */
    @PreAuthorize("@ss.hasPermi('compare:papers:remove')")
    @Log(title = "申论试卷", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(shenlunPapersService.deleteShenlunPapersByIds(ids));
    }

    /**
     * 获取申论试卷省份信息
     */
    @GetMapping("/category")
    public TableDataInfo getProvinces(ShenlunPapers shenlunPapers)
    {
        List<ShenlunPapers> list = shenlunPapersService.selectShenlunPapersList(shenlunPapers);

        // 假设 ShenlunPapers 类中有一个 getProvince() 方法来获取省份名称
        Map<String, Long> provinceCountMap = list.stream()
            .collect(Collectors.groupingBy(ShenlunPapers::getCategory, Collectors.counting()));

        // 将 Map 转换为 List
        List<Map<String, Object>> provinceCountList = new ArrayList<>();
        for (Map.Entry<String, Long> entry : provinceCountMap.entrySet()) {
            Map<String, Object> provinceInfo = new HashMap<>();
            provinceInfo.put("category", entry.getKey());
            provinceInfo.put("count", entry.getValue());
            provinceCountList.add(provinceInfo);
        }
        return getDataTable(provinceCountList);
    }
}
